import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:go_router/go_router.dart';
import 'package:http/http.dart' as http;
import 'package:my_ebook_app/models/catalogue.dart';
import 'package:my_ebook_app/pages/theme_notifier.dart';
import 'package:provider/provider.dart';
import 'package:my_ebook_app/models/book.dart';
import 'package:path/path.dart' as path;

import '../models/ReadingParams.dart';

class BookDetailPage extends StatefulWidget {
  final String bookName;

  BookDetailPage({required this.bookName});
  @override
  _BookDetailPage createState() => _BookDetailPage();
}
class _BookDetailPage extends State<BookDetailPage> with WidgetsBindingObserver{
  int _selectedIndex = 2;
  bool _isSettingsMenuOpen = false;
  late BookDetail bookDetail;
  late ReadingBook readingBook;
  late Catalogue bookCatalogue;
  final Map<String, double> bookCatalogues= {};
  List<String> bookTypes = [];
  bool _isLoading = true;
  String _errorMessage = '';
  bool _isRead = false;

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addObserver(this);
    _handlePressed();
  }

  void _handlePressed() {
    _fetchBookDetail();
  }
  void _handleReadingBook() async {
    await _fetchReadingBook();
    await _fetchBookCatalogue();
    final result = await context.push(
        '/reading', extra: ReadingParams(readingBook, bookCatalogue));

    if (result == 'progress_updated') {
      print('检测到进度更新，刷新书架数据');
      await _fetchBookDetail();
    } else {
      print('没有检测到进度更新');
    }
  }

  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    super.didChangeAppLifecycleState(state);
    if (state == AppLifecycleState.resumed) {
      _fetchReadingBook();
    }
  }
  // 从后端获取书籍详细信息
  Future<void> _fetchBookDetail() async {
    try {
      final response = await http.get(Uri.parse('http://10.0.2.2:8080/bookDetail?bookName=${widget.bookName}'));
      if (response.statusCode == 200) {
        final dynamic data = json.decode(response.body);
        bookDetail = BookDetail(
          title: data['bookName'],
          author: data['bookAuthor'],
          image: 'lib/common/images/${path.basename(data['bookCover'])}',
          rating: (data['bookRatings'] as num).toDouble(),
          type: data['bookType'],
          description: data['bookAbstract'],
          progress: (data['progress'] as num).toDouble(),
        );
        setState(() {
          _isLoading = false;
          _errorMessage = '';
        });
      } else {
        setState(() {
          _isLoading = false;
          _errorMessage = '加载失败: ${response.statusCode}';
        });
      }
    } catch (e) {
      print('错误: $e');
      setState(() {
        _isLoading = false;
        _errorMessage = '错误: $e';
      });
    }
    setState(() {
      if(bookDetail.progress > 0){
        _isRead = true;
      }
      else{
        _isRead = false;
      }
      bookTypes = bookDetail.type.split(',').map((type) => type.trim()).toList();
    });
  }
  Future<void> _fetchReadingBook() async {
    try {
      final response = await http.get(Uri.parse('http://10.0.2.2:8080/reading/info?bookName=${widget.bookName}'));

      if (response.statusCode == 200) {
        final dynamic data = json.decode(response.body);
        readingBook = ReadingBook(
          title: data['bookName'],
          totalChar: data['totalChar'],
          epubPath: data['bookAddress'],
          progress: (data['progress'] as num).toDouble(),
          localPath: data['localBookAddress'],
        );

        setState(() {
          _isLoading = false;
        });
      } else {
        setState(() {
          _isLoading = false;
          _errorMessage = '加载失败: ${response.statusCode}';
        });
      }
    } catch (e) {
      setState(() {
        _isLoading = false;
        _errorMessage = '错误: $e';
      });
    }
  }

  Future<void> _fetchBookCatalogue() async {
    try {
      final response = await http.get(Uri.parse('http://10.0.2.2:8080/reading/catalogue?bookName=${widget.bookName}'));

      if (response.statusCode == 200) {
        final dynamic data = json.decode(response.body);
        for( int i=0 ; i< data.length ; i++){
          bookCatalogues[data[i]['chapterName']] = (data[i]['chapterPosition'] as num).toDouble();
        }
        bookCatalogue = Catalogue(
          bookName: widget.bookName,
          bookCatalogues: bookCatalogues,
        );

        setState(() {
          _isLoading = false;
        });
      } else {
        setState(() {
          _isLoading = false;
          _errorMessage = '加载失败: ${response.statusCode}';
        });
      }
    } catch (e) {
      setState(() {
        _isLoading = false;
        _errorMessage = '错误: $e';
      });
    }
  }

  void _toggleSettingsMenu() {
    setState(() {
      _isSettingsMenuOpen = !_isSettingsMenuOpen;
    });
  }

  void _closeSettingsMenu() {
    if (_isSettingsMenuOpen) {
      setState(() {
        _isSettingsMenuOpen = false;
      });
    }
  }
  @override
  Widget build(BuildContext context) {
    final isDarkMode = Theme.of(context).brightness == Brightness.dark;
    // 显示加载状态
    if (_isLoading) {
      return Scaffold(
        body: Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              CircularProgressIndicator(),
              SizedBox(height: 20),
              Text('加载书籍信息中...'),
            ],
          ),
        ),
      );
    }
    // 显示错误信息
    if (_errorMessage.isNotEmpty) {
      return Scaffold(
        body: Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Text(_errorMessage),
              SizedBox(height: 20),
              ElevatedButton(
                onPressed: _handlePressed,
                child: Text('重试'),
              ),
            ],
          ),
        ),
      );
    }
    return GestureDetector(
      onTap: _closeSettingsMenu,
      child: Scaffold(
        body: SafeArea(
          child: Stack(
            children: [
              Column(
                children: [
                  // 页面顶部
                  SizedBox(
                    height: 35.0,
                    child: Row(
                      children: [
                        Padding(
                          padding: const EdgeInsets.only(left: 8.0),
                          child: IconButton(
                            icon: Icon(Icons.arrow_back,size: 18,),
                            onPressed: () => context.pop(),
                          ),
                        ),
                        Expanded(child: Container(),),
                        Padding(
                          padding: const EdgeInsets.only(right: 8.0),
                          child: IconButton(
                            icon: Icon(
                              Icons.settings_outlined,
                              size: 18,
                              color: _isSettingsMenuOpen ? Colors.grey[500] : null,
                            ),
                            onPressed: _toggleSettingsMenu,
                          ),
                        ),
                      ],
                    ),
                  ),
                  Expanded(
                    child: SingleChildScrollView(child: Padding(padding: const EdgeInsets.symmetric(horizontal: 18.0),
                        child: Column(crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            // 封面
                            Center(
                              child: ConstrainedBox(
                                  constraints: BoxConstraints(
                                    maxWidth: 300,
                                    maxHeight: 400,
                                  ),
                                  child: FractionallySizedBox(
                                    widthFactor: 0.75,
                                    heightFactor: 0.75,
                                    child: Container(
                                      decoration: BoxDecoration(
                                        image: DecorationImage(
                                          image: AssetImage(bookDetail.image),
                                          fit: BoxFit.cover,
                                          colorFilter: isDarkMode?
                                          ColorFilter.mode(
                                            Color(0x4D000000),
                                            BlendMode.darken,
                                          )
                                              :null,
                                        ),
                                        boxShadow: [
                                          BoxShadow(
                                            color: Colors.black54,
                                            blurRadius: 3,
                                            spreadRadius: 2,
                                          ),
                                        ],
                                      ),
                                    ),
                                  )
                              ),
                            ),
                            SizedBox(height: 20),
                            // 标题
                            Text(
                              bookDetail.title,
                              style: TextStyle(
                                fontSize: 28,
                                fontWeight: FontWeight.bold,
                              ),
                            ),
                            SizedBox(height: 5),
                            // 作者
                            Text(
                              bookDetail.author,
                              style: TextStyle(
                                fontSize: 15,
                                color: Colors.grey[500],
                              ),
                            ),
                            SizedBox(height: 5),
                            // 评分
                            Row(
                              children: List.generate(5, (index) {
                                return Icon(
                                  Icons.star,
                                  color: index < bookDetail.rating.round() ? Colors.amber : Colors.grey,
                                  size: 18,
                                );
                              }),
                            ),
                            SizedBox(height: 14),
                            // 类型
                            Row(
                              children: List.generate(bookTypes.length, (index) {
                                final textWidget = Text(
                                  bookTypes[index],
                                  style: const TextStyle(
                                    fontSize: 14,
                                    fontWeight: FontWeight.bold,
                                  ),
                                );
                                // 如果是最后一个元素，只返回文本（不加分隔线）
                                if (index == bookTypes.length - 1) {
                                  return textWidget;
                                }
                                // 非最后一个元素：文本 + 分隔线组合
                                return Row(
                                  children: [
                                    textWidget,
                                    const SizedBox(width: 10),
                                    Container(
                                      width: 1.0,
                                      height: 20.0,
                                      color: Colors.grey,
                                    ),
                                    const SizedBox(width: 10),
                                  ],
                                );
                              }).expand((widget) => widget is Row ? widget.children : [widget]).toList(),
                            ),
                            SizedBox(height: 14),
                            // 阅读按钮
                            Padding(
                              padding: EdgeInsets.only(top: 8, left: 10,right: 10),
                              child: Center(
                                child: Container(width: double.infinity, height: 45,
                                  decoration: BoxDecoration(
                                    border: Border.all(
                                      color: Color(0xFFFF3A7A), width: 1,
                                    ),
                                    borderRadius: BorderRadius.circular(8),
                                  ),
                                  child: TextButton.icon(
                                    onPressed: () => _handleReadingBook(),
                                    icon: Icon(Icons.library_books_outlined,
                                      color: Color(0xFFFF3A7A),
                                    ),
                                    label: Text(
                                      _isRead?'继续阅读':'阅读书籍',
                                      style: TextStyle(
                                        color: Color(0xFFFF3A7A), fontSize: 16,
                                      ),
                                    ),
                                  ),
                                ),
                              ),
                            ),
                            SizedBox(height: 16),
                            // 概要
                            Text(
                              '概要',
                              style: TextStyle(
                                fontSize: 18,
                                fontWeight: FontWeight.bold,
                              ),
                            ),
                            SizedBox(height: 8),
                            Text(
                              bookDetail.description,
                              style: TextStyle(
                                fontSize: 16,
                                color: Colors.grey[500],
                                height: 1.5,
                              ),
                            ),
                          ],
                        ),
                      ),
                    ),
                  ),
                ],
              ),

              // 设置菜单弹窗
              if (_isSettingsMenuOpen)
                Positioned(
                  top: 40,
                  right: 16,
                  child: Material(
                    elevation: 4,
                    borderRadius: BorderRadius.circular(8),
                    child: Container(
                      width: 200,
                      padding: EdgeInsets.all(12),
                      decoration: BoxDecoration(
                        borderRadius: BorderRadius.circular(8),
                        color: isDarkMode ? Color(0xFF32383E) : Color(0x80F6EEFA)
                      ),
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          // 深色模式开关
                          Row(
                            mainAxisAlignment: MainAxisAlignment.spaceAround,
                            children: [
                              Text("深色模式",
                                  style: TextStyle(
                                      fontSize: 16,
                                      fontWeight: FontWeight.bold
                                  )
                              ),
                              Transform.scale(
                                scale: 0.8,
                                child:  Consumer<ThemeNotifier>(
                                  builder: (context, themeNotifier, child) {
                                    return Transform.scale(
                                      scale: 0.8,
                                      child: Switch(
                                        value: themeNotifier.themeMode == ThemeMode.dark,
                                        onChanged: (value) {
                                          themeNotifier.setThemeMode(
                                              value ? ThemeMode.dark : ThemeMode.light
                                          );
                                        },
                                        activeColor: Colors.blue,
                                      ),
                                    );
                                  },
                                )
                              )
                            ],
                          ),

                          Divider(height: 18, thickness: 1),

                          // 退出登录按钮
                          InkWell(
                            onTap: () {
                              _closeSettingsMenu();
                              // 这里添加退出登录逻辑
                              context.push('/welcome');
                            },
                            child: Container(
                              padding: EdgeInsets.only(left: 5),
                              child: Padding(
                                padding: const EdgeInsets.symmetric(horizontal: 8.0),
                                child: Row(
                                  children: [
                                    Text("退出登录", style: TextStyle(fontSize: 16, color: Colors.red)),
                                    SizedBox(width: 40),
                                    Icon(Icons.exit_to_app, size: 26, color: Colors.red),
                                  ],
                                ),
                              )
                            ),
                          ),
                        ],
                      ),
                    ),
                  ),
                ),
            ],
          ),
        ),

        bottomNavigationBar: BottomNavigationBar(
          currentIndex: _selectedIndex,
          type: BottomNavigationBarType.fixed,
          unselectedLabelStyle: const TextStyle(fontSize: 10),
          selectedLabelStyle: const TextStyle(fontSize: 10),
          selectedItemColor: Colors.grey[600],
          unselectedItemColor: Colors.grey[600],
          items: const [
            BottomNavigationBarItem(
              icon: Icon(Icons.home_outlined),
              label: "首页",
            ),
            BottomNavigationBarItem(
              icon: Icon(Icons.menu_book_outlined),
              label: "书架",
            ),
            BottomNavigationBarItem(
              icon: Icon(Icons.book_outlined),
              label: "书",
            ),
          ],
          onTap: (int index) {
            setState(() {
              _selectedIndex = index;
            });
            switch(index){
              case 0:
                context.push('/home');
                break;
              case 1:
                context.push('/bookshelf');
                break;
              case 2:
                _handleReadingBook();
                break;
            }
          },
        ),
      ),
    );
  }
}

